import 'package:flutter/material.dart';

class AnimationControllerDemo extends StatefulWidget {
  static const String routeName = 'basics/animation_controller';

  const AnimationControllerDemo({super.key});

  @override
  State<AnimationControllerDemo> createState() =>
      _AnimationControllerDemoState();
}

class _AnimationControllerDemoState extends State<AnimationControllerDemo>
    with SingleTickerProviderStateMixin {
  late final AnimationController controller;
  static const Duration _duration = Duration(seconds: 1);
  @override
  void initState() {
    super.initState();
    controller = AnimationController(vsync: this, duration: _duration)
      // 每次Animation的值改变时，当前Widget的build方法都会被调用。因此在这里添加一个Listener
      // 并在Listener中调用SetState方法，如此就可以提醒Framework调孙build方法。
      // 如果build方法中的widget很简单，就可以选择该类。若是build中返回一个widget tree。并且
      // 该widget tree中的大部分child都没有动画效果，，可以考虑使用AnimatedBuilder类
      ..addListener(() {
        setState(() {});
      });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Animation Controller')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ConstrainedBox(
              constraints: const BoxConstraints(maxWidth: 200),
              child: Text(
                controller.value.toStringAsFixed(2),
                style: Theme.of(context).textTheme.displaySmall,
                textScaler: TextScaler.linear(1 + controller.value),
              ),
            ),
            ElevatedButton(
              onPressed: () {
                switch (controller.status) {
                  case AnimationStatus.completed:
                    controller.reverse();
                  default:
                    controller.forward();
                }
              },
              child: const Text('animate'),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    super.dispose();
    // AnimationController是一个stateful resource，当前State实例被dispose时，
    // 该controller实例也要被dispose
    controller.dispose();
  }
}
